#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Time    : 2025/9/26 17:36
# @Author  : WXY
# @File    : Splashcreen
# @PROJECT_NAME: youtubedown_gui
# @PRODUCT_NAME: PyCharm
# -------------------------------------------------------------------------------
import sys
import os
from PySide6.QtWidgets import QMainWindow, QApplication
from PySide6.QtCore import QTimer, QThread, Signal, Qt
from PySide6.QtGui import QPixmap, QPainter, QPainterPath, QRegion
from py_gui.splashscreen_ui import Ui_splashscreen

# 尝试导入资源文件，如果失败则跳过
try:
    from py_gui import resouce_rc  # 导入资源文件
    print("✅ 资源文件导入成功")
except ImportError as e:
    print(f"⚠️ 资源文件导入失败: {e}")

from utils import setup_label_icon, VERSION, setup_high_dpi_support, setup_window_title,setup_window_icon
from SettingsManager import settings_manager
from datetime import datetime, timedelta
from LoggerManager import logger_manager


class ModelLoadWorker(QThread):
    """模拟模型加载的工作线程"""
    progress_updated = Signal(int, str)
    finished = Signal()

    def run(self):
        """模拟加载过程"""
        try:
            stages = [
                (20, "正在初始化系统..."),
                (40, "正在加载配置文件..."),
                (60, "正在检查网络连接..."),
                (80, "正在准备用户界面..."),
                (100, "加载完成！")
            ]

            for progress, message in stages:
                self.progress_updated.emit(progress, message)
                self.msleep(300)  # 模拟加载时间

            self.finished.emit()

        except Exception as e:
            logger_manager.error(f"模型加载工作线程错误: {e}", "splash_screen")


class SplashScreen(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_splashscreen()
        self.ui.setupUi(self)

        # 设置窗口属性
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
        # self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

        # 设置窗口图标和标题
        setup_window_icon(self)
        setup_window_title(self)

        # 设置圆角
        self.set_rounded_corners()

        # 设置安全文本
        self.setup_safe_texts()

        # 设置Logo
        self.setup_logo()

        # 创建并启动工作线程
        self.worker = ModelLoadWorker()
        self.worker.progress_updated.connect(self.update_progress)
        self.worker.finished.connect(self.on_loading_finished)

        # 设置定时器来启动主窗口
        self.timer = QTimer()
        self.timer.timeout.connect(self.show_main_window)

        logger_manager.info("启动界面初始化完成", "splash_screen")

    def showEvent(self, event):
        """窗口显示事件"""
        super().showEvent(event)
        self.worker.start()

    def resizeEvent(self, event):
        """窗口大小改变事件"""
        super().resizeEvent(event)
        self.set_rounded_corners()

    def set_rounded_corners(self):
        """设置圆角"""
        try:
            radius = 15
            path = QPainterPath()
            path.addRoundedRect(self.rect(), radius, radius)
            region = QRegion(path.toFillPolygon().toPolygon())
            self.setMask(region)
        except Exception as e:
            logger_manager.error(f"设置圆角失败: {e}", "splash_screen")

    def get_logo_path(self):
        """获取Logo图片的正确路径"""
        try:
            # 在打包环境下
            if getattr(sys, 'frozen', False):
                # 从 _MEIPASS 获取
                logo_path = os.path.join(sys._MEIPASS, 'imgs', 'logo.png')
                if os.path.exists(logo_path):
                    return logo_path
            else:
                # 开发环境下的多个可能路径
                current_dir = os.path.dirname(os.path.abspath(__file__))
                possible_paths = [
                    os.path.join(os.path.dirname(current_dir), 'imgs', 'logo.png'),  # ../imgs/logo.png
                    os.path.join(current_dir, 'imgs', 'logo.png'),  # ./imgs/logo.png
                    "imgs/logo.png",  # 相对路径
                ]
                
                for path in possible_paths:
                    if os.path.exists(path):
                        return path
            
            return None
        except Exception as e:
            logger_manager.error(f"获取Logo路径失败: {e}", "splash_screen")
            return None

    def setup_safe_texts(self):
        """设置安全的文本内容"""
        try:
            # 设置版本信息
            self.ui.versionLabel.setText(f"版本 {VERSION}")

            # 设置状态文本
            self.ui.label.setText("正在启动...")

            # 设置进度条初始值
            self.ui.progressBar.setValue(0)

            # 设置样式
            self.ui.versionLabel.setStyleSheet("""
                QLabel {
                    color: rgba(255, 255, 255, 0.8);
                    font-size: 12px;
                    font-weight: normal;
                }
            """)

            self.ui.label.setStyleSheet("""
                QLabel {
                    color: rgba(255, 255, 255, 0.9);
                    font-size: 14px;
                    font-weight: bold;
                }
            """)

            # logger_manager.info("安全文本设置完成", "splash_screen")

        except Exception as e:
            logger_manager.error(f"设置安全文本失败: {e}", "splash_screen")

    def create_rounded_pixmap(self, pixmap, size):
        """创建圆角图片"""
        try:
            # 创建一个透明的图片
            rounded_pixmap = QPixmap(size)
            rounded_pixmap.fill(Qt.GlobalColor.transparent)

            # 创建画家
            painter = QPainter(rounded_pixmap)
            painter.setRenderHint(QPainter.RenderHint.Antialiasing)

            # 创建圆角路径
            path = QPainterPath()
            path.addRoundedRect(0, 0, size.width(), size.height(), 5, 5)

            # 设置裁剪路径
            painter.setClipPath(path)

            # 绘制缩放后的图片
            scaled_pixmap = pixmap.scaled(size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
            painter.drawPixmap(0, 0, scaled_pixmap)

            painter.end()
            return rounded_pixmap

        except Exception as e:
            logger_manager.error(f"创建圆角图片失败: {e}", "splash_screen")
            return pixmap

    def setup_logo(self):
        """设置Logo图片"""
        try:
            # 首先尝试从Qt资源系统加载
            try:
                pixmap = QPixmap(":/img/logo.png")
                if not pixmap.isNull():
                    # 创建圆角图片
                    rounded_pixmap = self.create_rounded_pixmap(pixmap, self.ui.logoLabel.size())
                    self.ui.logoLabel.setPixmap(rounded_pixmap)
                    self.ui.logoLabel.setStyleSheet("border-radius: 5px;")
                    return
            except Exception:
                pass

            # 如果资源加载失败，尝试加载本地文件
            logo_path = self.get_logo_path()
            if logo_path and os.path.exists(logo_path):
                pixmap = QPixmap(logo_path)
                if not pixmap.isNull():
                    # 创建圆角图片
                    rounded_pixmap = self.create_rounded_pixmap(pixmap, self.ui.logoLabel.size())
                    self.ui.logoLabel.setPixmap(rounded_pixmap)
                    self.ui.logoLabel.setStyleSheet("border-radius: 5px;")
                    logger_manager.info(f"Logo从本地路径加载成功: {logo_path}", "splash_screen")
                    return

            # 如果都失败了，使用emoji作为备用
            logger_manager.warning("Logo图片加载失败，使用默认图标", "splash_screen")
            self.ui.logoLabel.setText("🎬")
            self.ui.logoLabel.setStyleSheet("""
                QLabel {
                    color: white;
                    font-size: 32px;
                    border-radius: 5px;
                }
            """)

        except Exception as e:
            logger_manager.error(f"设置Logo失败: {e}", "splash_screen")
            # 最终备用方案
            self.ui.logoLabel.setText("🎬")
            self.ui.logoLabel.setStyleSheet("""
                QLabel {
                    color: white;
                    font-size: 32px;
                    border-radius: 5px;
                }
            """)

    def update_progress(self, value, message):
        """更新进度"""
        try:
            self.ui.progressBar.setValue(value)
            self.ui.label.setText(message)
        except Exception as e:
            logger_manager.error(f"更新进度失败: {e}", "splash_screen")

    def on_loading_finished(self):
        """加载完成"""
        try:
            # 延迟一点时间再启动主窗口
            self.timer.start(500)
        except Exception as e:
            logger_manager.error(f"加载完成处理失败: {e}", "splash_screen")

    def show_main_window(self):
        """显示主窗口"""
        try:
            self.timer.stop()

            # 导入并创建主窗口
            from Mainwindow import MainWindow
            self.main_window = MainWindow()
            self.main_window.show()

            # 关闭启动界面
            self.close()

            logger_manager.info("主窗口已启动，启动界面已关闭", "splash_screen")

        except Exception as e:
            logger_manager.error(f"显示主窗口失败: {e}", "splash_screen")
            # 如果主窗口启动失败，至少关闭启动界面
            self.close()


def main():
    """主函数"""
    # ✅ 在创建QApplication之前设置高DPI支持
    setup_high_dpi_support()
    
    app = QApplication(sys.argv)

    # 设置应用程序信息
    app.setApplicationName("YouTube视频下载器")
    app.setApplicationVersion(VERSION)

    try:
        splash = SplashScreen()
        splash.show()

        # 运行应用程序
        sys.exit(app.exec())

    except Exception as e:
        logger_manager.error(f"启动界面运行错误: {e}", "splash_screen")
        print(f"❌ 启动界面运行错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()